<template>
  <a-modal
    :open="open"
    @update:open="emit('update:open', $event)"
    title="手动配置"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form ref="formRef" :model="formState" :labelCol="{ span: 5 }">
      <a-form-item label="任务编号" name="id">
        <a-input v-model:value="formState.id" style="width: 300px" />
      </a-form-item>
      <a-form-item label="运单数量" name="transportOrderCount">
        <a-input v-model:value="formState.transportOrderCount" style="width: 300px" />
      </a-form-item>
      <a-form-item label="选择车次" name="transportTrips">
        <a-select v-model:value="formState.transportTrips" allowClear placeholder="请选择">
          <a-select-option v-for="(item, index) in transportTrips" :key="index" :value="index">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="选择车辆" name="['truck','id']">
        <a-select placeholder="请选择" allowClear v-model:value="formState.truck.id">
          <a-select-option v-for="(item, index) in carList" :key="index" :value="item.id">
            {{ item.licensePlate }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import {
  putTransportManagerAdjustByIdAPI,
  getTransportTaskManagerByIdAPI,
} from '@/services/transportManager.js'
import { getTruckPageAPI } from '@/services/truck.js'
import { message } from 'ant-design-vue'

const props = defineProps(['open', 'id'])
// 是否打开模态框-用于双向绑定
const emit = defineEmits(['update:open', 'ok'])

// 表单组件实例
const formRef = ref()

//
const transportTrips = ref([])

// 表单字段
const formState = ref({
  id: undefined,
  transportOrderCount: undefined,
  transportTrips: undefined,
  truck: { id: undefined },
})

const params = ref({
  page: 1,
  pageSize: 10,
})

// 车辆列表
const carList = ref([])
// console.log(props.id)

// 获取详情
const getDetail = async () => {
  const res = await getTransportTaskManagerByIdAPI(props.id)
  console.log(res)
  formState.value = res.data
  formState.value.id = res.data.id
  formState.value.transportTrips = res.data.transportTrips
  formState.value.truck.id = res.data.truck.id
}

// 获取车辆列表
const getCarList = async () => {
  const res = await getTruckPageAPI(params.value)
  // console.log(res)
  carList.value = res.data.items
}

// 确定按钮
const onOk = async () => {
  await putTransportManagerAdjustByIdAPI(
    formState.value.id,
    formState.value.transportTripsId,
    formState.value.truck.id,
  )
  message.success('手动调整成功')
  // 重置表单字段
  formRef.value.resetFields()
  // 关闭模态框
  emit('update:open', false)
  // 通知父组件，刷新表格数据
  emit('ok')
}

// 取消
const onCancel = () => {
  // 重置表单字段
  formRef.value.resetFields()
}
watch(
  () => [props.id, props.open],
  ([id]) => {
    if (id) {
      getDetail(id)
      getCarList()
    } else {
      formRef.value?.resetFields()
    }
  },
  {
    immediate: true,
  },
)
</script>
